<template>
  <div class="todo-component">
    <el-card class="todo-card" :class="{ 'edit-mode': isEditMode }">
      <!-- 编辑模式工具栏 -->
      <div v-if="isEditMode" class="component-toolbar">
        <el-button-group size="small">
          <el-button @click="$emit('configure-component', componentConfig)" icon="Setting" circle />
          <el-button @click="$emit('toggle-visibility')" :icon="component.visible ? 'View' : 'Hide'" circle />
          <el-button @click="$emit('remove')" icon="Delete" type="danger" circle />
        </el-button-group>
      </div>

      <!-- 组件标题 -->
      <template #header>
        <div class="card-header">
          <span class="card-title">{{ component.title }}</span>
          <div class="header-actions">
            <el-button @click="addTodo" size="small" icon="Plus" type="primary">
              添加任务
            </el-button>
            <el-dropdown @command="handleCommand">
              <el-button size="small" icon="More" circle />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="filter">筛选任务</el-dropdown-item>
                  <el-dropdown-item command="sort">排序</el-dropdown-item>
                  <el-dropdown-item command="export">导出</el-dropdown-item>
                  <el-dropdown-item command="clear" divided>清空已完成</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>

      <!-- 任务统计 -->
      <div class="todo-stats">
        <div class="stat-item">
          <span class="stat-label">总任务</span>
          <span class="stat-value">{{ todos.length }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">已完成</span>
          <span class="stat-value completed">{{ completedCount }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">进行中</span>
          <span class="stat-value pending">{{ pendingCount }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">逾期</span>
          <span class="stat-value overdue">{{ overdueCount }}</span>
        </div>
      </div>

      <!-- 进度条 -->
      <div class="progress-section">
        <div class="progress-info">
          <span>完成进度</span>
          <span>{{ completionPercentage }}%</span>
        </div>
        <el-progress 
          :percentage="completionPercentage" 
          :color="progressColor"
          :stroke-width="8"
        />
      </div>

      <!-- 任务筛选 -->
      <div class="todo-filters" v-if="showFilters">
        <el-radio-group v-model="currentFilter" size="small">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="pending">待办</el-radio-button>
          <el-radio-button label="completed">已完成</el-radio-button>
          <el-radio-button label="overdue">逾期</el-radio-button>
        </el-radio-group>
        <el-select v-model="priorityFilter" placeholder="优先级" size="small" style="width: 100px; margin-left: 8px;">
          <el-option label="全部" value="" />
          <el-option label="高" value="high" />
          <el-option label="中" value="medium" />
          <el-option label="低" value="low" />
        </el-select>
      </div>

      <!-- 任务列表 -->
      <div class="todo-list">
        <div 
          v-for="todo in filteredTodos" 
          :key="todo.id"
          class="todo-item"
          :class="{
            'completed': todo.completed,
            'overdue': isOverdue(todo),
            'high-priority': todo.priority === 'high',
            'medium-priority': todo.priority === 'medium',
            'low-priority': todo.priority === 'low'
          }"
        >
          <div class="todo-checkbox">
            <el-checkbox 
              v-model="todo.completed" 
              @change="updateTodo(todo)"
              :disabled="isOverdue(todo) && todo.completed"
            />
          </div>
          
          <div class="todo-content" @click="editTodo(todo)">
            <div class="todo-title" :class="{ 'completed': todo.completed }">
              {{ todo.title }}
            </div>
            <div class="todo-meta">
              <span class="todo-category" v-if="todo.category">
                <el-tag size="small" :type="getCategoryType(todo.category)">{{ todo.category }}</el-tag>
              </span>
              <span class="todo-priority">
                <el-tag size="small" :type="getPriorityType(todo.priority)">{{ getPriorityText(todo.priority) }}</el-tag>
              </span>
              <span class="todo-due-date" v-if="todo.dueDate">
                <el-icon><Calendar /></el-icon>
                {{ formatDate(todo.dueDate) }}
              </span>
              <span class="todo-assignee" v-if="todo.assignee">
                <el-icon><User /></el-icon>
                {{ todo.assignee }}
              </span>
            </div>
            <div class="todo-description" v-if="todo.description">
              {{ todo.description }}
            </div>
          </div>
          
          <div class="todo-actions">
            <el-button @click="editTodo(todo)" size="small" icon="Edit" circle />
            <el-button @click="deleteTodo(todo.id)" size="small" icon="Delete" type="danger" circle />
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-if="filteredTodos.length === 0" class="empty-state">
          <el-empty description="暂无任务" :image-size="80">
            <el-button @click="addTodo" type="primary">添加第一个任务</el-button>
          </el-empty>
        </div>
      </div>
    </el-card>
    
    <!-- 添加/编辑任务对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingTodo ? '编辑任务' : '添加任务'"
      width="500px"
    >
      <el-form :model="todoForm" :rules="todoRules" ref="todoFormRef" label-width="80px">
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="todoForm.title" placeholder="请输入任务标题" />
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input 
            v-model="todoForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入任务描述"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="todoForm.priority" placeholder="选择优先级">
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="todoForm.category" placeholder="选择分类" allow-create filterable>
            <el-option label="工作" value="work" />
            <el-option label="会议" value="meeting" />
            <el-option label="项目" value="project" />
            <el-option label="学习" value="study" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="截止日期">
          <el-date-picker
            v-model="todoForm.dueDate"
            type="datetime"
            placeholder="选择截止日期"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="todoForm.assignee" placeholder="选择负责人" filterable>
            <el-option label="张三" value="张三" />
            <el-option label="李四" value="李四" />
            <el-option label="王五" value="王五" />
            <el-option label="赵六" value="赵六" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTodo">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { Calendar, User, Plus, More, Edit, Delete, Setting, View, Hide } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  component: {
    type: Object,
    required: true
  },
  componentConfig: {
    type: Object,
    default: () => ({})
  },
  isEditMode: {
    type: Boolean,
    default: false
  }
})

defineEmits(['configure', 'toggle-visibility', 'remove', 'configure-component'])

// 响应式数据
const todos = ref([
  {
    id: 1,
    title: '完成月度销售报表',
    description: '整理本月销售数据，生成详细报表',
    priority: 'high',
    category: 'work',
    completed: false,
    dueDate: '2024-01-25 18:00:00',
    assignee: '张三',
    createdAt: '2024-01-20 09:00:00'
  },
  {
    id: 2,
    title: '客户需求调研会议',
    description: '与重要客户讨论新产品需求',
    priority: 'high',
    category: 'meeting',
    completed: false,
    dueDate: '2024-01-24 14:00:00',
    assignee: '李四',
    createdAt: '2024-01-22 10:30:00'
  },
  {
    id: 3,
    title: '更新产品文档',
    description: '更新产品使用手册和API文档',
    priority: 'medium',
    category: 'project',
    completed: true,
    dueDate: '2024-01-23 17:00:00',
    assignee: '王五',
    createdAt: '2024-01-21 11:00:00'
  },
  {
    id: 4,
    title: '库存盘点',
    description: '对仓库进行月度库存盘点',
    priority: 'medium',
    category: 'work',
    completed: false,
    dueDate: '2024-01-26 16:00:00',
    assignee: '赵六',
    createdAt: '2024-01-19 08:00:00'
  },
  {
    id: 5,
    title: '学习新技术',
    description: '学习Vue 3新特性和最佳实践',
    priority: 'low',
    category: 'study',
    completed: false,
    dueDate: '2024-01-30 20:00:00',
    assignee: '张三',
    createdAt: '2024-01-18 15:00:00'
  }
])

const dialogVisible = ref(false)
const editingTodo = ref(null)
const showFilters = ref(false)
const currentFilter = ref('all')
const priorityFilter = ref('')
const todoFormRef = ref()

// 表单数据
const todoForm = reactive({
  title: '',
  description: '',
  priority: 'medium',
  category: '',
  dueDate: '',
  assignee: ''
})

// 表单验证规则
const todoRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

// 计算属性
const completedCount = computed(() => todos.value.filter(todo => todo.completed).length)
const pendingCount = computed(() => todos.value.filter(todo => !todo.completed).length)
const overdueCount = computed(() => todos.value.filter(todo => isOverdue(todo) && !todo.completed).length)
const completionPercentage = computed(() => {
  if (todos.value.length === 0) return 0
  return Math.round((completedCount.value / todos.value.length) * 100)
})

const progressColor = computed(() => {
  const percentage = completionPercentage.value
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
})

const filteredTodos = computed(() => {
  let filtered = todos.value
  
  // 按状态筛选
  if (currentFilter.value === 'pending') {
    filtered = filtered.filter(todo => !todo.completed)
  } else if (currentFilter.value === 'completed') {
    filtered = filtered.filter(todo => todo.completed)
  } else if (currentFilter.value === 'overdue') {
    filtered = filtered.filter(todo => isOverdue(todo) && !todo.completed)
  }
  
  // 按优先级筛选
  if (priorityFilter.value) {
    filtered = filtered.filter(todo => todo.priority === priorityFilter.value)
  }
  
  return filtered.sort((a, b) => {
    // 优先级排序
    const priorityOrder = { high: 3, medium: 2, low: 1 }
    if (a.priority !== b.priority) {
      return priorityOrder[b.priority] - priorityOrder[a.priority]
    }
    // 截止日期排序
    if (a.dueDate && b.dueDate) {
      return new Date(a.dueDate) - new Date(b.dueDate)
    }
    return 0
  })
})

// 方法
const isOverdue = (todo) => {
  if (!todo.dueDate || todo.completed) return false
  return new Date(todo.dueDate) < new Date()
}

const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  const now = new Date()
  const diffTime = date - now
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) return '今天'
  if (diffDays === 1) return '明天'
  if (diffDays === -1) return '昨天'
  if (diffDays > 0) return `${diffDays}天后`
  return `${Math.abs(diffDays)}天前`
}

const getPriorityType = (priority) => {
  const types = { high: 'danger', medium: 'warning', low: 'info' }
  return types[priority] || 'info'
}

const getPriorityText = (priority) => {
  const texts = { high: '高', medium: '中', low: '低' }
  return texts[priority] || '中'
}

const getCategoryType = (category) => {
  const types = { 
    work: 'primary', 
    meeting: 'warning', 
    project: 'success', 
    study: 'info', 
    other: '' 
  }
  return types[category] || ''
}

const addTodo = () => {
  editingTodo.value = null
  resetForm()
  dialogVisible.value = true
}

const editTodo = (todo) => {
  editingTodo.value = todo
  Object.assign(todoForm, {
    title: todo.title,
    description: todo.description,
    priority: todo.priority,
    category: todo.category,
    dueDate: todo.dueDate,
    assignee: todo.assignee
  })
  dialogVisible.value = true
}

const saveTodo = async () => {
  try {
    await todoFormRef.value.validate()
    
    if (editingTodo.value) {
      // 编辑任务
      Object.assign(editingTodo.value, todoForm)
      ElMessage.success('任务更新成功')
    } else {
      // 添加任务
      const newTodo = {
        id: Date.now(),
        ...todoForm,
        completed: false,
        createdAt: new Date().toISOString()
      }
      todos.value.unshift(newTodo)
      ElMessage.success('任务添加成功')
    }
    
    dialogVisible.value = false
    resetForm()
  } catch {
    // 验证失败
  }
}

const deleteTodo = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个任务吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = todos.value.findIndex(todo => todo.id === id)
    if (index > -1) {
      todos.value.splice(index, 1)
      ElMessage.success('任务删除成功')
    }
  } catch {
    // 用户取消
  }
}

const updateTodo = (todo) => {
  if (todo.completed) {
    ElMessage.success('任务已完成')
  }
}

const resetForm = () => {
  Object.assign(todoForm, {
    title: '',
    description: '',
    priority: 'medium',
    category: '',
    dueDate: '',
    assignee: ''
  })
  todoFormRef.value?.clearValidate()
}

const handleCommand = (command) => {
  switch (command) {
    case 'filter':
      showFilters.value = !showFilters.value
      break
    case 'sort':
      ElMessage.info('排序功能开发中...')
      break
    case 'export':
      ElMessage.info('导出功能开发中...')
      break
    case 'clear':
      clearCompleted()
      break
  }
}

const clearCompleted = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有已完成的任务吗？', '确认清空', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    todos.value = todos.value.filter(todo => !todo.completed)
    ElMessage.success('已清空完成的任务')
  } catch {
    // 用户取消
  }
}
</script>

<style scoped>
.todo-component {
  position: relative;
}

.todo-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.todo-card.edit-mode {
  border: 2px dashed #409eff;
  position: relative;
}

.todo-card.edit-mode:hover {
  border-color: #67c23a;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.component-toolbar {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 6px;
  padding: 4px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.todo-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-item {
  text-align: center;
}

.stat-label {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-value {
  display: block;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.stat-value.completed {
  color: #67c23a;
}

.stat-value.pending {
  color: #409eff;
}

.stat-value.overdue {
  color: #f56c6c;
}

.progress-section {
  margin-bottom: 16px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.todo-filters {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.todo-list {
  max-height: 400px;
  overflow-y: auto;
}

.todo-item {
  display: flex;
  align-items: flex-start;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  margin-bottom: 8px;
  transition: all 0.3s ease;
  background: white;
}

.todo-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.todo-item.completed {
  background: #f0f9ff;
  border-color: #67c23a;
}

.todo-item.overdue {
  border-color: #f56c6c;
  background: #fef0f0;
}

.todo-item.high-priority {
  border-left: 4px solid #f56c6c;
}

.todo-item.medium-priority {
  border-left: 4px solid #e6a23c;
}

.todo-item.low-priority {
  border-left: 4px solid #909399;
}

.todo-checkbox {
  margin-right: 12px;
  margin-top: 2px;
}

.todo-content {
  flex: 1;
  cursor: pointer;
}

.todo-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  line-height: 1.4;
}

.todo-title.completed {
  text-decoration: line-through;
  color: #909399;
}

.todo-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
  flex-wrap: wrap;
}

.todo-due-date,
.todo-assignee {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.todo-description {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
  margin-top: 4px;
}

.todo-actions {
  display: flex;
  gap: 4px;
  margin-left: 8px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

@media (max-width: 768px) {
  .todo-stats {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .header-actions {
    flex-direction: column;
    gap: 4px;
  }
  
  .todo-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .todo-actions {
    flex-direction: column;
  }
}
</style>